<!DOCTYPE html>
<html lang="en">
<head>
    <title>管理系统 - 管理中心</title>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <!-- <meta ng-include="'head.html'"> -->
    <style type="text/css">

    </style>
    <script src="../lib/js/jquery.min.js" type="text/javascript"></script>
    <script src="../js/build.js" type="text/javascript"></script>
    <script src="../js/public.js" type="text/javascript"></script>
</head>
<body class="flat-blue">
<div class="app-container" ng-app="myApp" ng-controller="myCtrl">
<div class="row content-container">
<div ng-include="'menus.html'" onload="loadReady()"></div>
<div class="container-fluid">
<div class="side-body padding-top" id="main">
    <!------------------Main---------------->
    <div style="width:90%; margin:10px 10px 10px 0px; padding:0px 0px 30px 20px">
        <table class="table" data-show-toggle="false" data-expand-first="true">
            <thead>
            <tr>
                <th ng-show="false">ID</th>
                <th>序号</th>
                <th>字段</th>
                <th data-breakpoints="xs">控件</th>
                <th ng-show="false">fieldName</th>
                <th>名称</th>
                <th>输入提示</th>
                <th>是否必填</th>
                <th data-breakpoints="xs sm">预览</th>
                <th>操作</th>
                <th>排序</th>
            </tr>
            </thead>
            <tbody>
            <tr ng-repeat="row in rows" on-finish-render-filters class="{{row.enable ? 'rowEnable' : 'rowDisabled'}}" ng-if="row.name!=''">
                <td>{{row.index}}</td>
                <td>{{row.fieldName}}</td>
                <!-- 类型 -->
                <td>{{typeText[row.type]}}</td>
                <!-- 名称可编辑 -->
                <td>
                    <span ng-show="row.editFlag[0]">
                        <span class="info mr">{{row.name}}</span>
                        <span class="glyphicon glyphicon-edit" ng-click="editSwitch($index, 0)"></span>
                    </span>
                    <span ng-show="!row.editFlag[0]">
                        <input type="text" ng-model="row.name" >
                        <button ng-click="editSwitch($index, 0)" class="bt btn btn-default btn-xs">
                            <span class="glyphicon glyphicon-ok"></span> 完成
                        </button>
                    </span>
                </td>
                <!-- 功能描述可编辑 -->
                <td>
                    <span ng-show="row.editFlag[1]">
                        {{row.describe}}
                        <span class="ml glyphicon glyphicon-edit" ng-click="editSwitch($index, 1)"></span>
                    </span>
                    <span ng-show="!row.editFlag[1]">
                        <input type="text" ng-model="row.describe" >
                        <button ng-click="editSwitch($index, 1)" class="bt btn btn-default btn-xs">
                            <span class="glyphicon glyphicon-ok"></span> 完成
                        </button>
                    </span>
                </td>
                <!-- 是否必填 -->
                <td>
                    <input type="radio" value="true" ng-model="row.notNull" name="{{row.field}}">是
                    <input type="radio" value="false" ng-model="row.notNull" name="{{row.field}}">否
                </td>
                <!-- 预览 · 编辑 -->
                <td ng-switch="row.type">
                    <div ng-switch-when="text">
                        <input style="width:190px" type="text" placeholder="{{row.describe}}" >
                    </div>
                    <!-- 单选按钮 -->
                    <div ng-switch-when="radio">
                        <span ng-repeat="sel in selOptions[row.field]" ng-if="sel.name!=''">
                            <input type="radio" value="false" name="{{row.field}}_r" >{{sel.name}}
                        </span>
                        <button class="bt btn btn-info btn-xs" data-toggle="modal" data-target="#myModal1" ng-click="beforeModal(row.field)">
                            <span class="glyphicon glyphicon-pencil"></span> 编辑
                        </button>
                    </div>
                    <!-- 下拉列表 -->
                    <div ng-switch-when="select">
                        <select ng-model='x' ng-options="x.name for x in selOptions[row.field]"></select>
                        <button class="bt btn btn-info btn-xs" data-toggle="modal" data-target="#myModal1" ng-click="beforeModal(row.field)">
                            <span class="glyphicon glyphicon-pencil"></span> 编辑
                        </button>
                    </div>
                    <!-- 时间选择框 -->
                    <div ng-switch-when="time">
                        <div class="input-group date" data-date-format="yyyy-mm-dd" style="margin-top:4px">
                            <input class="form-control" size="14" type="text" value="2017-01-01" style="height: 30px; width:100px">
                        <span class="input-group-addon bg-light btn-sm f" >
                            <span class="glyphicon glyphicon glyphicon-time" style="font-size: 10px"></span>
                        </span>
                        </div>
                    </div>
                    <!--地址选择组件-->
                    <div ng-switch-when="address" style="margin-top: 3px">
                        <select ng-model="Addrs[row.field].selProvince" style="width:80px; float:left" ng-change="selectChina(0, row.field);"
                                ng-options="x for x in Addrs[row.field].libs.provinces"></select>
                        <select ng-model="Addrs[row.field].selCity" style="width:80px; float:left" ng-change="selectChina(1, row.field);"
                                ng-options="x for x in Addrs[row.field].libs.citys"></select>
                        <select ng-model="Addrs[row.field].selCounty" style="width:80px; float:left"
                                ng-options="x for x in Addrs[row.field].libs.countys"></select>
                    </div>
                </td>
                <!--是否启用该字段-->
                <td>
                    <span ng-show="row.enable" class="pointer primary" title="点击切换状态">
                        <span class="glyphicon glyphicon-ok-circle" ng-click="changeEnable($index)"></span>
                    </span>
                    <span ng-show="!row.enable" class="pointer danger" title="点击切换状态">
                        <span class="glyphicon glyphicon-ban-circle" ng-click="changeEnable($index)"></span>
                    </span>
                    <span class="pointer danger ml" title="删除该字段">
                        <span class="glyphicon glyphicon-remove-circle" ng-click="removeField($index)"></span>
                    </span>
                </td>
                <!--排序-->
                <td>
                    <span class="glyphicon glyphicon-arrow-up pointer sort" ng-click="changeIndex($index, 1)"></span>
                </td>
            </tr>
            </tbody>
        </table>

        <!-- End Table -->
        <div class="col-sm-12" align="left" style="margin-top:10px;float:none">
            <button type="button" class="btn btn-default btn-sm" ng-click="addRow()">
                <span class="glyphicon glyphicon-plus"></span> 增加新行
            </button>
        </div>
        <div class="col-sm-12" align="right" style="margin-top:10px;float:none">
            <button type="button" class="btn btn-default" ng-click="cancel()">取消</button>
            <button type="button" class="btn btn-primary" ng-click="Submit()">提交</button>
        </div>

        <div ng-include="'modalEditList.html'"></div>
        <div ng-include="'modalNewField.html'"></div>
        
    </div>
    <!------------------End Main---------------------->
</div>  <!--End side-body-->
</div>  <!--End container-fluid-->
</div>  <!--End content-container-->
<div ng-include="'footer.html'"></div>
</div>  <!--End app-container-->

<script language="javascript">
    var app = angular.module('myApp', []);
    app.controller('myCtrl', function($scope) {
        loadCtlBase($scope);
        
        //// 调整顺序
        $scope.changeIndex = function (index, order){
            if((index==0 && order) || (index==$scope.rows.length && !order))return;
            var target = order ? index-1 : index+1;
            var row = $scope.rows[target];
            $scope.rows[target] = $scope.rows[index];
            $scope.rows[index] = row;
            $scope.rows[index].index = index;
            $scope.rows[target].index = target;
        };
        $scope.changeEnable = function (index){
            $scope.rows[index].enable = !$scope.rows[index].enable;
        };
        
        $scope.rows = [];
        //// 地址控件集
        $scope.Addrs = {};
        //// 通用模态框，根据modalField键加载相应内容
        $scope.modalField = "";
        $scope.beforeModal = function(field){ $scope.modalField = field;  };
        //// 编辑状态切换
        $scope.selFlag = {};
        $scope.typeList = [["text", "文本框"], ["select","下拉列表"], ["radio","选择按钮"], ["time","时间控件"],
            ["address","下拉选择"]];
        $scope.typeText = $scope.typeList.reduce(function(a, b){ a[b[0]]=b[1]; return a; }, {});

        //// 空闲系统字段
        //$scope.fieldUnUsed = {};
        //// 新增字段
        $scope.field = {};
        $scope.changeFieldSel = function(){
            if($scope.field.field==='')$scope.field.name = "";
            else{
                $scope.field.name = $scope.cols[$scope.field.field].name; // $scope.fieldUnUsed[$scope.field.field].name;
                $scope.field.fieldName = $scope.field.name;
            }
        };
        function getNewColName(){
            for(var key in $scope.cols){
                if('isUsed' in $scope.cols[key] && $scope.cols[key]['isUsed']==1)continue;
                if(key.length>3 && key.substr(0, 3)=="col")return key;
            }
            return null;
        }
        function getNewRow(){
            var row = {
                'id':-1, 'describe':'无', 'enable':true, 'notNull':'false',
                'editFlag':[1, 1], 'index':$scope.rows.length, 'type':'text',
                'field':'', 'name':'', 'fieldName':'自定义'
            };
            return row;
        }
        function getRowIndex(field){
            for(var i = 0; i<$scope.rows.length; i++)if($scope.rows[i].field===field)return i;
            return -1;
        }
        /*
            新增及删除逻辑：
                1、字段增加：先检查rows里是否有，有则放出来，无则push
                2、字段删除：原有字段则只清名称，新增字段则splice删除
            逻辑结果：
                1、检查原字段名是否为空，作为删除依据
         */
        $scope.addField = function(){
            if($scope.field.fieldName===''){
                alert("字段名不能为空");
                return;
            }
            if($scope.field.field==="") $scope.field.field = getNewColName();
            var index = getRowIndex($scope.field.field);
            if(index==-1)
                $scope.rows.push($scope.field);
            else{
                $scope.rows[index].name = $scope.field.fieldName;
                $scope.rows[index].type = $scope.field.type;
            }
            $scope.cols[$scope.field.field]['isUsed'] = 1;
            $scope.field = getNewRow();
            $("#myModal2").modal('hide');
        };
        //// 删除字段
        $scope.removeField = function(index){
            if(!confirm("你确信要删除该字段吗？"))return;
            $scope.rows[index].name = "";
            $scope.cols[$scope.rows[index].field]['isUsed'] = 0;
            if($scope.rows[index].id==-1)$scope.rows.splice(index, 1);
        };

        ////// 获取配置信息
        ajaxData("get_form", {"user":'David'}, function(rst){ cout(rst);
            var cacheTemp = {};
            $scope.rows = rst.data.rows;
            $scope.cols = rst.data.cols;
            $scope.selOptions = rst.data.options;
            $scope.rows.forEach(function(d, i){
                cacheTemp[d.field] = 1;
                $scope.cols[d.field]['isUsed'] = 1;
                d['index'] = i;
                d['editFlag'] = [1, 1];
                if(d.type=="address"){
                    //// 地址联动组件，selProvince， selCity， selCounty为选择或设置的值
                    $scope.Addrs[d.field] = {"selProvince":"", "selCity":"", "selCounty":""};
                }

            });
            // for(var key in $scope.cols)if(!(key in cacheTemp))$scope.fieldUnUsed[key] = $scope.cols[key];

            for(var key in $scope.selOptions)
                $scope.selFlag[key] = $scope.selOptions[key].map(function(){ return true;});
            //// 加载地址控件
            loadAddrs($scope, $scope.Addrs);
            $scope.$apply();
            cout($scope.selFlag);
        });

        for(var key in $scope.selOptions)
            $scope.selFlag[key] = $scope.selOptions[key].map(function(){ return true;});
        //// name编辑状态切换
        $scope.editSwitch = function(index, i){
            $scope.rows[index].editFlag[i] = !$scope.rows[index].editFlag[i];
        };
        //// 列表编辑状态切换
        $scope.editList = function(key, index){
            $scope.selFlag[key][index] = !$scope.selFlag[key][index];
        };
        //// 列表删除
        $scope.delOption = function(key, index) {
            $scope.selOptions[key][index]['name'] = '';
            //// 若有问题请不执行下句
            if($scope.selOptions[key][index]['id']==-1)$scope.selOptions[key].splice(index, 1);
        };
        //// 列表新增
        $scope.addOption = function(key) {
            if($scope.newOption=='')return;
            if(!(key in $scope.selOptions))$scope.selOptions[key] = [];
            $scope.selOptions[key].push({name:$scope.newOption, id:-1});
            $scope.selFlag[key].push(true);
            $scope.newOption = "";
        };

        //// 增加字段
        $scope.addRow = function(){
            $scope.field = getNewRow();
            $("#myModal2").modal('show');
        };



        // //// 地址联动组件，selProvince， selCity， selCounty为选择或设置的值
        // $scope.Addrs = { "address":{"selProvince":"", "selCity":"", "selCounty":""}, "address2":{} };
        // loadAddrs($scope, $scope.Addrs);

        $scope.Submit = function(){
            var keys = ["id", "index", "field", "fieldName", "name", "describe", "type", "notNull", 
                        "enable"];
            var lines = $scope.rows.map(function(d){
                return keys.reduce(function(a, b){ a[b] = d[b]; return a; }, {});
            });
            var options = angular.toJson($scope.selOptions);
            ajaxData("set_form", {rows:JSON.stringify(lines), options:options}, function(dt){
                cout(dt);
                if(dt.error===false)window.location.reload();
            });
        
        };

    });

    app.directive('onFinishRenderFilters', function ($timeout) {
        return {
            restrict: 'A',
            link: function ($scope, element, attr) {
                if ($scope.$last !== true)return;
                $timeout(function () {
                    $('.date').datetimepicker({
                        format: 'yyyy-mm-dd', language:'zh-CN', autoclose:true, minView:"month"
                    });            
                 });
            }
        }
    });

    $(document).ready(function(){
        $('.date').datetimepicker({
            format: 'yyyy-mm-dd', language:'zh-CN', autoclose:true, minView:"month"
        });
    });    



</script>

</body>
</html>
